import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
// 重写push 方法，防止因为版本问题抛出错误
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
	if (onResolve || onReject)
		return originalPush.call(this, location, onResolve, onReject)
	return originalPush.call(this, location).catch((err) => err)
}
// 重写repalce 方法，防止因为版本问题抛出错误
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace(location, onResolve, onReject) {
	if (onResolve || onReject)
		return originalReplace.call(this, location, onResolve, onReject)
	return originalReplace.call(this, location).catch((err) => err)
}

Vue.use(VueRouter)

const routes = [
	{
		path: '/login',
		name: 'Login',
		component: () =>
			import(/* webpackChunkName: "login" */ '@/views/login'),
	},
	{
		path: '/',
		name: 'Layout',
		redirect: '/home',
		component: () =>
			import(/* webpackChunkName: "layout" */ '@/views/layout'),
		children: [
			{
				path: '/home',
				name: 'Home',
				component: () =>
					import(/* webpackChunkName: "home" */ '@/views/home'),
			},
			{
				path: '/qa',
				name: 'Qa',
				component: () =>
					import(/* webpackChunkName: "qa" */ '@/views/qa'),
			},
			{
				path: '/video',
				name: 'Video',
				component: () =>
					import(/* webpackChunkName: "video" */ '@/views/video'),
			},
			{
				path: '/user',
				name: 'User',
				component: () =>
					import(/* webpackChunkName: "user" */ '@/views/user'),
			},
		],
	},
	{
		path: '/user/collect',
		name: 'UserCollect',
		component: () =>
			import(/* webpackChunkName: "userCollect" */ '@/views/user/user-collect'),
		meta: { needLogin: true },
	},
	{
		path: '/user/history',
		name: 'UserHistory',
		component: () =>
			import(/* webpackChunkName: "userHistory" */ '@/views/user/user-history'),
		meta: { needLogin: true },
	},
  {
		path: '/user/profile',
		name: 'UserProfile',
		component: () =>
			import(/* webpackChunkName: "UserProfile" */ '@/views/user-profile'),
		meta: { needLogin: true },
	},
  {
		path: '/search',
		name: 'Search',
		component: () =>
			import(/* webpackChunkName: "search" */ '@/views/search'),
	},
  {
		path: '/article/:articleId',
		name: 'Article',
		component: () =>
			import(/* webpackChunkName: "article" */ '@/views/article'),
    props:true  // 通过props解耦动态参数
	}
]

const router = new VueRouter({
	routes,
})

// 导航守卫
router.beforeEach((to, from, next) => {
	if (to.meta.needLogin) {
		// 要登录才可以访问
		if (store.getters.haslogin) {
			// 已登录放行
			next()
		} else {
			// 未登录，去登录页
			next('/login?url=' + to.path)
		}
	} else {
		// 要去的地址不要登录就可以访问
		next()
	}
})

export default router
